package com.migo.api;

import com.migo.annotation.IgnoreAuth;
import com.migo.entity.SysOssEntity;
import com.migo.entity.UserinfoInternationEntity;
import com.migo.oss.OSSFactory;
import com.migo.service.SysOssService;
import com.migo.service.UserinfoInternationService;
import com.migo.utils.R;
import com.migo.utils.RRException;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;

/**
 * Created by Wes on 2018/11/19.
 */
@CrossOrigin
@RestController
@RequestMapping("/api")
public class ApiCommonController {

    private Logger logger = Logger.getLogger(getClass());
    @Autowired
    OSSFactory ossFactory;

    @Autowired
    private SysOssService sysOssService;


    @Autowired
    private UserinfoInternationService userinfoInternationService;
    /**
     * 上传文件
     */
    @IgnoreAuth
    @RequestMapping("/upload")
    public R upload(@RequestParam("file") MultipartFile file,@RequestParam("userId") String userId) throws Exception {

        String fileName = "";
        if (file.isEmpty()) {
            throw new RRException("上传文件不能为空");
        }
        //通过用户验证身份信息，来保护文件上传的安全
        UserinfoInternationEntity user  = userinfoInternationService.queryUser(userId);
        if(user!=null)
        {
            fileName = file.getOriginalFilename();
            String url = ossFactory.build().upload(fileName,file.getBytes());
            logger.info("URL : "+url);
            SysOssEntity ossEntity = new SysOssEntity();
            ossEntity.setUrl(url);
            ossEntity.setCreateDate(new Date());
            sysOssService.save(ossEntity);

            logger.info("OSSENTITY : "+ossEntity);
            return R.ok().put("data", ossEntity);
        }
        return R.error();

    }


}
